import { generator, notFoundRouter } from '@/utils/permissions'
import { get } from '@/utils/ajax'
const user = {
  state: {
    token: '',
    name: '',
    welcome: '',
    avatar: '',
    roles: [],
    info: {},
    login: false,
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, { name, welcome }) => {
      state.name = name
      state.welcome = welcome
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_INFO: (state, info) => {
      state.info = info
    },
    SET_LOGIN: (state, info) => {
      state.login = info
    },
  },

  actions: {
    // 获取用户信息
    GetInfo({ commit }) {
      return new Promise((resolve, reject) => {
        get('/api/user/user_nav').then((res) => {
          console.log(res)
          if (res.status === 401) {
            reject(new Error('您还未登入'))
          } else {
            commit('SET_INFO', res.info)
            let roles = {
              permissions: res.auth
            }
            commit('SET_ROLES', roles)
            // commit('SET_WS', res.info)
            const routers = generator(res.nav)
            routers.push(notFoundRouter)
            resolve(routers)
          }
        })
      })
    },

    // 登出
    Logout({ commit, state }) {
      get('/api/user/logout').then((res) => {
        commit('SET_LOGIN', false)
      })
    },
  },
}

export default user
